package com.zxd.admin.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ding.login.service.IRecordLoginService;
import com.hs.common.api.dto.ResultVo;
import com.hs.jwt.JwtTemplate;
import com.hs.order.exception.Asserts;
import com.zxd.admin.constant.RedisConstant;
import com.zxd.admin.constant.UserConstant;
import com.zxd.admin.dto.AdminDto;
import com.zxd.admin.entity.Admin;
import com.zxd.admin.mapper.AdminMapper;
import com.zxd.admin.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Dong
 * @since 2022-07-22
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtTemplate jwtTemplate;


    /**
     * 用户认证:
     * 1、根据用户名查询
     * 2、判断：用户名校验、密码校验
     * 3、校验成功，生成token
     * 4、token存储到redis中，设置有效时间
     * 5、返回token
     */

    @Override
    public String login(AdminDto adminDto) {

        //根据用户名查询
        LambdaQueryWrapper<Admin> wrapper = Wrappers.lambdaQuery(Admin.class);
        wrapper.eq(Admin::getUsername,adminDto.getUsername());
        Admin admin = this.getOne(wrapper);

        //判断
        if(Objects.isNull(admin)){
            Asserts.failed("用户名或密码不存在！");
        }

//        if(!admin.getPassword().equals(adminDto.getPassword())){
//            Asserts.failed("用户名或密码不存在！");
//        }

        if (!BCrypt.checkpw(adminDto.getPassword(),admin.getPassword())){
            // 密码校验失败
            Asserts.failed("用户名或密码不存在！");
        }


        //校验成功

        //保存登录信息到库中


        Map<String,Object> playload = new HashMap<>();
        playload.put(UserConstant.USER_ID,admin.getId());
        String token = jwtTemplate.createToken(playload);

        //token存到redis中
        redisTemplate.opsForValue().set(
                RedisConstant.USER_TOKEN + admin.getId(),token, Duration.ofMinutes(30)
        );

        //返回token
        return token;
    }

    @Override
    public ResultVo findAdminByName(String username) {

        LambdaQueryWrapper<Admin> query = Wrappers.lambdaQuery(Admin.class);
        query.eq(Admin::getUsername,username);
        Admin admin = getOne(query);
        return new ResultVo(admin);

    }

}
